package com.ruoyi.common.core.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.page.BaseQuery;
import com.ruoyi.common.core.utils.sql.SqlUtil;
import com.ruoyi.common.core.web.page.CommonPageInfo;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableSupport;
import java.util.List;
import java.util.Optional;

/**
 * 分页工具类
 *
 * @author ruoyi
 */
public class PageUtils extends PageHelper {

  /**
   * 设置请求分页数据
   */
  public static <T> CommonPageInfo<T> startPage() {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();
    String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
    Boolean reasonable = pageDomain.getReasonable();
    PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    return initPageInfo(pageNum, pageSize);
  }

  /**
   * 设置请求分页数据
   */
  public static <T> CommonPageInfo<T> startPage(BaseQuery query) {
    return startPage(query.getPageNum(), query.getPageSize());
  }

  /**
   * 设置请求分页数据
   */
  public static <T> CommonPageInfo<T> startPage(Integer pageNum, Integer pageSize) {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    pageNum = Optional.ofNullable(pageNum).orElse(pageDomain.getPageNum());
    pageSize = Optional.ofNullable(pageSize).orElse(pageDomain.getPageSize());
    String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
    Boolean reasonable = pageDomain.getReasonable();
    PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    return initPageInfo(pageNum, pageSize);
  }

  private static <T> CommonPageInfo<T> initPageInfo(Integer pageNum, Integer pageSize) {
    final CommonPageInfo<T> tPageInfo = new CommonPageInfo<T>();
    tPageInfo.setPages(pageNum);
    tPageInfo.setPageSize(pageSize);
    return tPageInfo;
  }

  /**
   * 设置请求分页数据
   */
  public static <E> Page<E> getHelper() {
    final PageDomain pageDomain = TableSupport.buildPageRequest();
    return PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(),
        SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()));
  }

  /**
   * 设置请求分页数据
   */
  public static <E> Page<E> getHelper(Integer pageNum, Integer pageSize) {
    final PageDomain pageDomain = TableSupport.buildPageRequest();
    return PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(),
        SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()));
  }


  /**
   * 清理分页的线程变量
   */
  public static void clearPage() {
    PageHelper.clearPage();
  }

  /**
   * 计算总数,用于分页数据获得总数
   *
   * @param list 列表
   * @return 总数量
   */
  public static <E> long getTotal(List<E> list) {
    return new PageInfo<E>(list).getTotal();
  }

}
